package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {
	
	/**
	 * 校验jwt
	 *
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		//判断当前拦截到的是Controller的方法还是其他资源
		if (!(handler instanceof HandlerMethod)) {
			//当前拦截到的不是动态方法，直接放行
			log.info("放行非动态方法");
			return true;
		}
		
		Claims claims = JwtUtil.getClaimsBody(request.getHeader("authentication"));
		int UserId = JwtUtil.verifyToken(claims);
		Long id = null;
		if (claims != null) {
			id = claims.get(JwtClaimsConstant.ID, Long.class);
		}
		//简单地防止一下越权
		//如果有登录数据，代表一登录，放行
		if ((UserId == -1 || UserId == 0)) {
			BaseContext.setCurrentId(id);
			return true;
		} else {
			//否则，发送未认证错误信息
			response.setStatus(401);
			return false;
		}
	}
}
